package service;
import pojo.Location;

import java.time.LocalDateTime;
import java.time.LocalTime;

public class ClockInService {
    private static final double WORK_LATITUDE = 31.2304;
    private static final double WORK_LONGITUDE = 121.4737;
    private static final double RADIUS_IN_DEGREES = 0.001;
    // 大约对应100米的距离
    private static final LocalTime START_TIME = LocalTime.of(8, 0);
    private static final LocalTime END_TIME = LocalTime.of(10, 0);
    private EmployeeService employeeService;
    private TimeService timeService;
    private LocationService locationService;

    public ClockInService(EmployeeService employeeService, TimeService timeService, LocationService locationService) {
        this.employeeService = employeeService;
        this.timeService = timeService;
        this.locationService = locationService;
    }

    public boolean clockIn(String employeeId) {
        if (!employeeService.isEmployee(employeeId)) {
            return false;
        }
        LocalDateTime currentTime = timeService.getCurrentTime();
        LocalTime currentLocalTime = currentTime.toLocalTime();
        if (currentLocalTime.isBefore(START_TIME) || currentLocalTime.isAfter(END_TIME)) {
            return false;
        }
        Location currentLocation = locationService.getCurrentLocation();
        return isWithinWorkArea(currentLocation);
    }

    private boolean isWithinWorkArea(Location location) {
        double distance = calculateDistance(location.getLatitude(), location.getLongitude(), WORK_LATITUDE, WORK_LONGITUDE);
        return distance <= RADIUS_IN_DEGREES;
    }

    private double calculateDistance(double lat1, double lon1, double lat2, double lon2) {
        // 使用Haversine公式计算两点之间的距离
        double earthRadius = 6371;
        // 地球平均半径，单位为公里
        double dLat = Math.toRadians(lat2 - lat1);
        double dLon = Math.toRadians(lon2 - lon1);
        double a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2)) * Math.sin(dLon / 2) * Math.sin(dLon / 2);
        double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
        double distanceInKm = earthRadius * c;
        return distanceInKm / 111.32; // 将距离转换为经纬度差
         } }

